<template>
    <div class="warp">
        <!-- 聊天列表 -->
        <div class="chats-list">
            <!-- 搜索 -->
            <div class="search">
                <input
                    type="search"
                    id="search"
                    v-model="searchUser"
                    placeholder="通信编号搜索"
                />
            </div>
            <!-- 列表 -->
            <div class="list">
                <template v-if="userList.length > 0">
                    <div
                        :class="{
                            'list-item': true,
                            'chats-avtive':
                                item.visitorid == chatInfo.visitorid,
                        }"
                        v-for="(item, index) in userList"
                        :title="getListUserTitle(item)"
                        @click="selectUser(item)"
                    >
                        <div class="chats">
                            <div class="chats-avatar">
                                <img :src="item.avatar" alt="avatar" />
                                <div
                                    v-show="item.showHot"
                                    class="chats-hot"
                                ></div>
                                <!-- <div class="chats-num">10</div> -->
                            </div>
                            <div class="chats-content">
                                <div class="chats-user-title">
                                    <div class="username">
                                        {{ getListUserTitle(item) }}
                                    </div>
                                    <div class="usertime">
                                        {{ getLastChatTime(item) }}
                                    </div>
                                </div>
                                <div class="chats-user-msg">
                                    <span>{{ getLastChatMsg(item) }}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </template>
                <template v-else>
                    <!-- 暂无数据 -->
                    <div class="not-data">暂无记录</div>
                </template>
            </div>
        </div>
        <!-- 聊天内容 -->
        <div class="chat-content">
            <div v-show="userList.length > 0 && useChat">
                <!-- 头部 -->
                <div class="header">
                    <!-- 公司应用名称 -->
                    <div class="title">{{ headerTitle }}</div>
                    <!-- 用户名称 -->
                    <div class="user-setting" @click="getUserInfo">
                        <i id="userInfo-btn" class="iconfont icon-user"></i>
                    </div>
                </div>
                <!-- 左侧 -->
                <!-- 聊天内容 -->
                <div class="content chatMessage" id="content">
                    <template v-for="(item, index) in chats">
                        <div :class="item.type">
                            <div
                                v-html="item.content"
                                :class="{ message: item.message }"
                            ></div>
                        </div>
                    </template>

                    <div class="clearfix" id="end_content"></div>
                </div>
                <!-- 聊天输入框 -->
                <div class="save">
                    <!-- 小工具 -->
                    <div class="chat-tools">
                        <!-- emoji -->
                        <span
                            class="chat-tools-btn"
                            title="选择表情"
                            id="emoji-btn"
                        >
                            <i class="iconfont icon-emoji"></i>
                        </span>
                        <span
                            class="chat-tools-btn"
                            title="图文信息"
                            id="news-btn"
                            @click="news"
                        >
                            <i class="iconfont icon-news"></i>
                        </span>
                        <!-- link -->
                        <span
                            class="chat-tools-btn"
                            title="网址链接"
                            id="link-btn"
                            @click="showLinkDialog"
                        >
                            <i class="iconfont icon-link"></i>
                        </span>
                        <!-- file -->
                        <span
                            class="chat-tools-btn"
                            title="发送文件"
                            id="upload-btn"
                            v-if="config.uploadLink"
                        >
                            <i class="iconfont icon-filepackage"></i>
                        </span>
                        <!-- 访客转接 -->
                        <span
                            class="chat-tools-btn"
                            title="访客转接"
                            id="transfer-btn"
                            @click="transfer"
                        >
                            <i class="iconfont icon-transfer"></i>
                        </span>
                    </div>
                    <!-- 输入框 -->
                    <div class="text">
                        <textarea
                            id="text-input"
                            v-model="content"
                            placeholder="请输入要发送的消息..."
                        ></textarea>
                    </div>
                    <!-- 发送框 -->
                    <div class="footer">
                        <span class="chat-btn close" @click="onClose">
                            关闭(<u>C</u>)
                        </span>
                        <span class="chat-btn send" id="send" @click="send">
                            发送(<u>S</u>)
                        </span>
                    </div>

                    <!-- 表情包选择框 -->
                    <div id="emoji"></div>
                </div>
                <!-- 用户信息 -->
                <div id="user-bar" v-show="showUserInfo">
                    <div class="user-info">
                        <div class="user-info-item">
                            <input
                                type="text"
                                name="username"
                                placeholder="姓名"
                                v-model="userInfo.username"
                            />
                        </div>
                        <div class="user-info-item">
                            <input
                                type="text"
                                name="email"
                                placeholder="邮箱"
                                v-model="userInfo.email"
                            />
                        </div>
                        <div class="user-info-item">
                            <input
                                type="text"
                                name="phone"
                                placeholder="手机"
                                v-model="userInfo.moble"
                            />
                        </div>
                        <div class="user-info-item">
                            <input
                                type="text"
                                name="qq"
                                placeholder="QQ"
                                v-model="userInfo.qq"
                            />
                        </div>
                        <div class="user-info-item">
                            <input
                                type="text"
                                name="address"
                                placeholder="地址"
                                v-model="userInfo.address"
                            />
                        </div>
                        <div class="user-info-item">
                            <textarea
                                name="remark"
                                placeholder="备注"
                                v-model="userInfo.remark"
                            ></textarea>
                        </div>
                        <div class="user-info-item">
                            <span class="user-info-btn" @click="saveUserInfo"
                                >保存</span
                            >
                        </div>
                    </div>
                </div>
            </div>
            <!-- 暂无数据 -->
            <div class="not-data" v-show="!useChat || userList.length <= 0">
                暂无记录
            </div>
        </div>
        <div class="clearfix"></div>
        <!-- 链接弹窗 -->
        <mDialog
            v-model="showLink"
            :type="'links'"
            @ok="linkSuccess"
            @cancel="linkCancel"
        ></mDialog>
        <!-- 提示弹窗 -->
        <mDialog v-model="showAlert" :msg="alertMsg" @ok="alertClose"></mDialog>
        <!-- 断开连接提示弹窗 -->
        <mDialog
            v-model="showClose"
            type="confirm"
            msg="确认要结束关闭会话么？"
            @ok="close"
            @cancel="showClose = false"
        ></mDialog>
        <!-- 转接弹窗 -->
        <mDialog
            v-model="showTransfer"
            type="confirm"
            title="客服转接"
            @ok="sendTransfer"
            @cancel="
                showTransfer = false;
                transferTarget = [];
                transferList = [];
            "
        >
            <p class="text-error" style="text-align: left">
                {{ transferError }}
            </p>
            <mSelect
                placeholder="请选择转接的客服"
                v-model="transferTarget"
                style="width: 100%"
                :options="transferOptions"
            />
        </mDialog>
        <!-- 图文弹窗 -->
        <mDialog
            v-model="showNews"
            type="confirm"
            id="news"
            title="图文信息列表"
            @ok="sendNews"
            @cancel="
                showNews = false;
                newsTarget = [];
                newsList = [];
            "
        >
            <p class="text-error" style="text-align: left">
                {{ newsError }}
            </p>
            <mSelect
                placeholder="请选择发送的图文信息"
                v-model="newsTarget"
                style="width: 100%"
                :options="newsOptions"
                @change="newsChange"
            />
            <div class="chatMessage" v-html="newsPreview"></div>
        </mDialog>
    </div>
</template>
<script>
import Api from "page/api";
import Util from "common/util";
import {
    MonDialog as mDialog,
    MonLoadingModal as LoadingModal,
    MonSelect as mSelect,
} from "mon-util";
import chatMixins from "common/mixins/chat/index";
export default {
    name: "home",
    mixins: [chatMixins],
    components: {
        mDialog,
        mSelect,
    },
    data() {
        return {
            // 配置信息
            config: window.config,
            // 用户搜索
            searchUser: "",
            // 用户源数据列表
            dataList: [],
            // 聊天内容板
            useChat: false,
            // 聊天窗
            chatInfo: {},
            // 显示用户信息
            showUserInfo: false,
            // 用户信息
            userInfo: {},
            // 转移窗口
            showTransfer: false,
            // 允许转移的客服列表
            transferList: [],
            // 转接的客服
            transferTarget: [],
            // 转接的错误信息
            transferError: "",
            // 图文选择窗口
            showNews: false,
            // 图文列表
            newsList: [],
            // 选择的图文信息
            newsTarget: [],
            // 图文信息的错误信息
            newsError: "",
            // 图文预览
            newsPreview: "",
        };
    },
    computed: {
        // 用户列表
        userList() {
            let search = this.searchUser;
            if (!search) {
                return this.dataList;
            } else {
                let data = this.dataList.filter((item) => {
                    return item.id == search;
                });

                return data;
            }
        },
        // 聊天窗户标题
        headerTitle() {
            return (
                this.chatInfo.app_title +
                " - 访客" +
                this.chatInfo.id +
                " [" +
                this.chatInfo.ip +
                "]"
            );
        },
        // 格式化的转移列表
        transferOptions() {
            return this.transferList.map((item) => {
                return {
                    uid: item.uid,
                    title: item.account + " - " + item.nickname,
                };
            });
        },
        // 格式化的图文列表
        newsOptions() {
            let visitorid = this.chatInfo.visitorid;
            return this.newsList.map((item) => {
                item.visitorid = visitorid;
                return item;
            });
        },
    },
    mounted() {
        // 初始化表情包
        this._initEmoji();
        // 初始化文件上传
        if (this.config.uploadLink) {
            this._initUpload();
        }
        // 从缓存中获取chatConfig
        this.chatConfig.uid = Util.getStorage("chat_kefu_uid", null, false);
        // 初始化websocket
        this._initWebsocket();
    },
    methods: {
        // 初始化websocket链接
        _initWebsocket() {
            // 初始化websocket
            if (window.WebSocket) {
            } else if (window.MozWebSocket) {
                window.WebSocket = MozWebSocket;
            } else {
                this.showAlertDialog(
                    "您正在使用过时的浏览器，是时候更换一个更好的浏览器来提升用户体验！"
                );
                return;
            }
            this.ws = new WebSocket(this.config.server);
            this.ws.onopen = () => {
                let data = {
                    cmd: this.config.cmd,
                    type: "login",
                    app: this.config.app,
                    uid: this.config.uid,
                };
                this.ws.send(JSON.stringify(data));
                // 设置心跳
                setInterval(() => {
                    this.ws.send(
                        JSON.stringify({
                            cmd: this.config.cmd,
                            type: "ping",
                        })
                    );
                }, 50000);
            };
            this.ws.onmessage = (e) => {
                let res = JSON.parse(e.data);
                if (res.code == "200") {
                    let data = res.data;
                    switch (data.type) {
                        case "transfer":
                            // 标志游客已转移
                            this.chatInfo.transfer = true;
                            this.dataList = this.dataList.map((item) => {
                                if (item.visitorid == data.visitor) {
                                    item.transfer = true;
                                }
                                return item;
                            });
                            // 重置信息
                            this.transferError = "";
                            this.showTransfer = false;
                            this.transferList = [];
                            LoadingModal.finish();
                            this.chat_tips(data.msg);
                            let temp = chatMessage.parse("tips", {
                                content: data.msg || "客户已转接",
                            });
                            this.chats.push({
                                type: "tips",
                                message: false,
                                content: temp,
                            });
                            break;
                        case "tips":
                        case "img":
                        case "text":
                        case "news":
                            if (data.visitid == this.chatConfig.group) {
                                let date = Util.formatDate(
                                    this.getLastChatTime(data)
                                );
                                let send =
                                    data.from == this.chatConfig.uid
                                        ? "ask"
                                        : "reply";
                                let sdk = chatMessage.setPath(
                                    "/static/libs/monEmoji/img/"
                                );

                                let content = sdk.parse(
                                    data.type,
                                    data,
                                    date,
                                    send
                                );
                                this.chats.push({
                                    type: send,
                                    message: false,
                                    content: content,
                                });
                            }
                            this.signal(data);
                            break;
                        case "load":
                            // 加载客户列表
                            this.dataList = data.list;
                            break;
                        case "waiter_transfer":
                            // 客服转接
                            let existsTransfer = this.dataList.some((item) => {
                                return item.visitorid == data.client_uid;
                            });
                            if (!existsTransfer) {
                                this.dataList.unshift({
                                    visitorid: data.client_uid,
                                    app: data.app,
                                    app_title: data.app_title,
                                    avatar: data.avatar,
                                    ip: data.ip,
                                    id: data.id,
                                    showHot: true,
                                    time: data.time,
                                    transfer: false,
                                });
                            } else {
                                this.dataList = this.dataList.map((item) => {
                                    if (item.visitorid == data.client_uid) {
                                        item.showHot = true;
                                        item.transfer = false;
                                    }

                                    return item;
                                });
                                if (data.client_uid == this.chatConfig.group) {
                                    let temp = chatMessage.parse("tips", {
                                        content: data.msg || "客户转接已链接",
                                    });
                                    this.chats.push({
                                        type: "tips",
                                        message: false,
                                        content: temp,
                                    });
                                }
                            }
                            break;
                        case "visitor":
                            // 客户发起通信
                            let exists = this.dataList.some((item) => {
                                return item.visitorid == data.client_uid;
                            });
                            if (!exists) {
                                this.dataList.unshift({
                                    visitorid: data.client_uid,
                                    app: data.app,
                                    app_title: data.app_title,
                                    avatar: data.avatar,
                                    ip: data.ip,
                                    id: data.id,
                                    showHot: true,
                                    time: data.time,
                                    transfer: false,
                                });
                            } else {
                                this.dataList = this.dataList.map((item) => {
                                    if (item.visitorid == data.client_uid) {
                                        item.showHot = true;
                                        item.transfer = false;
                                    }

                                    return item;
                                });
                                if (data.client_uid == this.chatConfig.group) {
                                    // this.chat_tips(data.msg || "客户已链接");
                                    let temp = chatMessage.parse("tips", {
                                        content: data.msg || "客户已链接",
                                    });
                                    this.chats.push({
                                        type: "tips",
                                        message: false,
                                        content: temp,
                                    });
                                }
                            }
                            break;
                        case "visitorExit":
                            let client = data.client;
                            if (client == this.chatConfig.group) {
                                // this.chat_tips(data.msg || "客户已断开连接");
                                let temp = chatMessage.parse("tips", {
                                    content: data.msg || "客户已断开连接",
                                });
                                this.chats.push({
                                    type: "tips",
                                    message: false,
                                    content: temp,
                                });
                            }
                            // 游客退出
                            break;
                    }
                } else if (res.code == "401") {
                    window.location.href = this.config.login;
                } else {
                    this.showAlertDialog(res.msg);
                }
            };
            this.ws.onerror = (event) => {
                console.log(event);
                this.showAlertDialog("链接客服中心异常，请稍后再试。");
            };
            this.ws.onclose = () => {
                this.showAlertDialog("客服中心链接已断开, 请重新登录");
            };
        },
        // 发送信息
        send() {
            if (this.content.trim() == "") {
                return false;
            }
            if (!this.ws) {
                this.showAlertDialog("未成功链接客服中心，请稍后再试");
                return false;
            }
            let data = {
                cmd: this.config.cmd,
                type: "send",
                dataType: "text",
                content: this.content,
                to: this.chatConfig.group,
                app: this.chatInfo.app,
            };
            this.sendData(data);
            this.content = "";
        },
        // 客服转移
        transfer() {
            this.transferError = "";
            this.transferList = [];
            let app = this.chatInfo.app;
            Api.transfer(app).then((res) => {
                if (res.code == "1") {
                    this.transferList = res.data;
                    this.showTransfer = true;
                } else {
                    this.transferError = "暂无可转接的客服在线";
                }
            });
        },
        // 提交客服转接
        sendTransfer() {
            if (!this.transferTarget[0]) {
                this.transferError = "请选择转接的客服人员";
                return false;
            }
            let transferTarget = this.transferTarget[0].uid;
            LoadingModal.start();
            let data = {
                cmd: this.config.cmd,
                type: "transfer",
                visitor: this.chatInfo.visitorid,
                target: transferTarget,
            };
            this.sendData(data);
        },
        // 打开图文弹窗
        news() {
            this.newsError = "";
            this.newsList = [];
            this.newsPreview = "";
            let app = this.chatInfo.app;
            Api.news(app).then((res) => {
                if (res.code == "1") {
                    this.newsList = res.data;
                    this.showNews = true;
                } else {
                    this.newsError = "获取图文列表失败";
                }
            });
        },
        // 发送图文信息
        sendNews() {
            if (!this.newsTarget[0]) {
                this.newsError = "请选择要发送的图文信息";
                return false;
            }

            let data = {
                cmd: this.config.cmd,
                type: "send",
                dataType: "news",
                content: this.newsTarget[0],
                to: this.chatConfig.group,
                app: this.chatInfo.app,
            };
            this.sendData(data);
            this.showNews = false;
            this.newsError = "";
            this.newsList = [];
            this.newsPreview = "";
        },
        //选择图文
        newsChange(data, item) {
            console.log(item);
            let tmp = chatMessage.parse("news", { content: item }, "预览");
            this.newsPreview = tmp;
        },
        // 获取显示在列表的用户名称
        getListUserTitle(item) {
            return item.app_title + " - 访客" + item.id;
        },
        // 获取显示在列表的用户最后聊天时间
        getLastChatTime(item) {
            let date = item.time || "";
            return Util.formatDate(date, "H-i");
        },
        // 获取显示在列表的用户最新聊天记录
        getLastChatMsg(item) {
            let msg = item.lastMsg || "";
            return msg;
        },
        // 点击列表，选中用户
        selectUser(item) {
            if (item.visitorid == this.chatConfig.group) {
                return false;
            }
            this.showUserInfo = false;
            this.useChat = true;
            this.chatInfo = item;
            this.chatConfig.group = item.visitorid;
            this.dataList = this.dataList.map((result) => {
                if (item.visitorid == result.visitorid) {
                    result.showHot = false;
                }
                return result;
            });
            // 异步加载聊天记录
            Api.pull(item.app, item.visitorid, this.chatConfig.uid).then(
                (result) => {
                    let data = result.data;
                    this.initList(data);
                }
            );
        },
        // 获取用户信息
        getUserInfo() {
            if (!this.showUserInfo) {
                // 异步获取用户信息
                Api.getClientInfo(this.chatConfig.group).then((result) => {
                    this.userInfo = result.data;
                });
            }

            this.showUserInfo = !this.showUserInfo;
        },
        // 保存用户信息
        saveUserInfo() {
            Api.saveClientInfo(this.chatConfig.group, this.userInfo).then(
                (result) => {
                    this.$Toastr.send("保存客户信息成功");
                }
            );
        },
        // 关闭会话
        close() {
            let data = this.chatInfo;
            this.dataList = this.dataList.filter((item) => {
                return item.visitorid != data.visitorid;
            });
            this.showClose = false;
            this.useChat = false;
            this.chatInfo = {};
            this.chatConfig.group = null;
            // 发送会话结束指令
            let result = {
                cmd: this.config.cmd,
                type: "close",
                to: data.visitorid,
            };
            // this.ws.send(JSON.stringify(result));
            this.sendData(result);
        },
        // 处理通话信息提示
        signal(data) {
            if (data.from != this.chatConfig.uid) {
                this.dataList = this.dataList.map((item) => {
                    if (data.from == item.visitorid) {
                        if (data.from != this.chatConfig.group) {
                            item.showHot = true;
                        }
                        item.time = data.time;
                        if (data.type == "text") {
                            item.lastMsg = data.content;
                        } else if (data.type == "img") {
                            item.lastMsg = "发送了一张图片...";
                        } else if (data.type == "news") {
                            item.lastMsg = "发送了图文信息";
                        }
                    }
                    return item;
                });
            }
        },
    },
};
</script>
<style>
#news .dialog-confirm {
    max-width: 360px;
}
</style>